package com.hadluo.qq.client.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.client.ui.LoginFrame;
import com.hadluo.qq.client.utils.Constants;

public class RegisterFrame extends JFrame {
    private JTextField nicknameField;
    private JPasswordField passwordField;
    private JComboBox<String> genderComboBox;
    private JTextField avatarField;
    private JTextArea signatureArea;
    private JButton registerButton;
    private JLabel avatarPreview; // 添加头像预览标签

    public RegisterFrame() {
        setTitle("注册");
        setSize(600, 700); // 增加窗口大小
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        getContentPane().setBackground(new Color(35, 35, 35)); // 设置深色背景

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));
        mainPanel.setBackground(new Color(35, 35, 35)); // 设置深色背景

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(new Color(35, 35, 35)); // 设置深色背景
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10);

        // 添加标题
        JLabel titleLabel = new JLabel("账号注册", SwingConstants.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE); // 设置白色文字
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 30, 0);
        formPanel.add(titleLabel, gbc);
        gbc.gridwidth = 1;

        // 重置内边距
        gbc.insets = new Insets(10, 10, 10, 10);

        // 添加昵称输入框
        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel nicknameLabel = new JLabel("昵称:");
        nicknameLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        nicknameLabel.setForeground(Color.WHITE); // 设置白色文字
        formPanel.add(nicknameLabel, gbc);

        gbc.gridx = 1;
        nicknameField = new JTextField(20);
        styleTextField(nicknameField);
        formPanel.add(nicknameField, gbc);

        // 添加密码输入框
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        passwordLabel.setForeground(Color.WHITE); // 设置白色文字
        formPanel.add(passwordLabel, gbc);

        gbc.gridx = 1;
        passwordField = new JPasswordField(20);
        styleTextField(passwordField);
        formPanel.add(passwordField, gbc);

        // 添加性别选择框
        gbc.gridx = 0;
        gbc.gridy = 3;
        JLabel genderLabel = new JLabel("性别:");
        genderLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        genderLabel.setForeground(Color.WHITE); // 设置白色文字
        formPanel.add(genderLabel, gbc);

        gbc.gridx = 1;
        genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        styleComboBox(genderComboBox);
        formPanel.add(genderComboBox, gbc);

        // 添加头像选择按钮
        gbc.gridx = 0;
        gbc.gridy = 4;
        JLabel avatarLabel = new JLabel("头像:");
        avatarLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        avatarLabel.setForeground(Color.WHITE); // 设置白色文字
        formPanel.add(avatarLabel, gbc);

        gbc.gridx = 1;
        JPanel avatarPanel = new JPanel(new BorderLayout(10, 0));
        avatarPanel.setBackground(new Color(35, 35, 35)); // 设置深色背景

        // 创建头像预览面板
        avatarPreview = new JLabel();
        avatarPreview.setPreferredSize(new Dimension(100, 100));
        avatarPreview.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));
        avatarPreview.setHorizontalAlignment(SwingConstants.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        buttonPanel.setBackground(new Color(35, 35, 35));

        // 添加选择图片按钮
        JButton chooseAvatarButton = new JButton("选择图片");
        styleButton(chooseAvatarButton);
        buttonPanel.add(chooseAvatarButton);

        // 使用GridBagLayout重新组织avatarPanel
        avatarPanel.setLayout(new GridBagLayout());
        GridBagConstraints avatarGbc = new GridBagConstraints();

        // 添加头像预览
        avatarGbc.gridx = 0;
        avatarGbc.gridy = 0;
        avatarGbc.insets = new Insets(0, 0, 5, 0);
        avatarPanel.add(avatarPreview, avatarGbc);

        // 添加按钮面板
        avatarGbc.gridy = 1;
        avatarGbc.fill = GridBagConstraints.HORIZONTAL;
        avatarPanel.add(buttonPanel, avatarGbc);

        formPanel.add(avatarPanel, gbc);

        // 添加个性签名输入区
        gbc.gridx = 0;
        gbc.gridy = 5;
        JLabel signatureLabel = new JLabel("个性签名:");
        signatureLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        signatureLabel.setForeground(Color.WHITE); // 设置白色文字
        formPanel.add(signatureLabel, gbc);

        gbc.gridx = 1;
        signatureArea = new JTextArea(6, 30); // 增加文本框大小
        signatureArea.setLineWrap(true);
        signatureArea.setWrapStyleWord(true);
        signatureArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        signatureArea.setBackground(Color.WHITE);
        signatureArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)
        ));
        JScrollPane signatureScrollPane = new JScrollPane(signatureArea);
        signatureScrollPane.setBorder(null);
        formPanel.add(signatureScrollPane, gbc);

        // 添加注册按钮
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(30, 10, 10, 10);
        registerButton = new JButton("立即注册");
        styleRegisterButton(registerButton);
        formPanel.add(registerButton, gbc);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        add(mainPanel);

        // 删除重复的头像预览代码
        // 更新头像选择事件
        chooseAvatarButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter(
                    "图片文件", "jpg", "jpeg", "png", "gif"));

            if (fileChooser.showOpenDialog(RegisterFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    // 准备上传文件
                    java.io.File file = fileChooser.getSelectedFile();
                    String boundary = Long.toHexString(System.currentTimeMillis());

                    // 创建连接
                    URL url = new URL("http://"+ Constants.SERVER_HOST+":8080/api/file/upload");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                    try (OutputStream os = conn.getOutputStream();
                         java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file)) {

                        // 写入文件数据
                        byte[] boundary_bytes = ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
                        byte[] content_disposition = ("Content-Disposition: form-data; name=\"file\"; filename=\"" +
                                file.getName() + "\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8);

                        os.write(boundary_bytes);
                        os.write(content_disposition);

                        // 写入文件内容
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }

                        // 写入结束标记
                        os.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
                    }

                    // 处理响应
                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            // 解析响应获取URL
                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            String fileUrl = jsonResponse.getString("url");
                            // 确保URL以http开头
                            if (!fileUrl.startsWith("http")) {
                                fileUrl = "http://"+Constants.SERVER_HOST+":8080" + fileUrl;
                            }
                            // 更新头像预览
                            try {
                                ImageIcon imageIcon = new ImageIcon(new URL(fileUrl));
                                Image image = imageIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
                                avatarPreview.setIcon(new ImageIcon(image));
                                // 存储头像URL供注册使用
                                avatarPreview.setName(fileUrl);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                            JOptionPane.showMessageDialog(RegisterFrame.this,
                                    "头像上传成功",
                                    "成功",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        throw new Exception("文件上传失败: " + responseCode);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(RegisterFrame.this,
                            "上传头像失败: " + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 保持原有的注册按钮事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String nickname = nicknameField.getText();
                String password = new String(passwordField.getPassword());


                if (nickname.isEmpty() || password.isEmpty() || avatarPreview.getName().isEmpty()) {
                    JOptionPane.showMessageDialog(RegisterFrame.this,
                            "昵称，密码和头像不能为空",
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 发送注册请求
                try {
                    // 使用FastJSON创建请求JSON
                    JSONObject requestJson = new JSONObject();
                    requestJson.put("nickname", nickname);
                    requestJson.put("password", password);
                    if(genderComboBox.getSelectedItem().toString().equals("男")){
                        requestJson.put("gender", 1);
                    }else{
                        requestJson.put("gender", 0);
                    }
                    requestJson.put("avatar", avatarPreview.getName());
                    requestJson.put("signature", signatureArea.getText());
                    String jsonInputString = requestJson.toString();

                    URL url = new URL("http://"+Constants.SERVER_HOST+":8080/api/user/register");
                    System.out.println("发送请求到: " + url.toString());
                    System.out.println("请求参数: " + jsonInputString);

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setDoOutput(true);

                    try (OutputStream os = conn.getOutputStream()) {
                        byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                        os.write(input, 0, input.length);
                    }

                    int responseCode = conn.getResponseCode();
                    System.out.println("响应状态码: " + responseCode);

                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }
                            System.out.println("响应内容: " + response.toString());

                            // 使用FastJSON解析响应
                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            boolean success = jsonResponse.getBoolean("success");
                            String message = jsonResponse.getString("message");

                            if (success) {
                                // 从data字段中获取服务器返回的QQ号
                                JSONObject data = jsonResponse.getJSONObject("data");
                                String qqNumber = data.getString("qqNumber");
                                // 显示QQ号提示信息
                                JOptionPane.showMessageDialog(RegisterFrame.this,
                                        "您的QQ号为 " + qqNumber + "，请妥善保管",
                                        "注册成功",
                                        JOptionPane.INFORMATION_MESSAGE);

                                // 关闭注册窗口
                                dispose();

                                // 打开登录窗口并预填充QQ号
                                SwingUtilities.invokeLater(() -> {
                                    LoginFrame loginFrame = new LoginFrame();
                                    loginFrame.setQQNumber(qqNumber);
                                    loginFrame.setVisible(true);
                                });
                            } else {
                                JOptionPane.showMessageDialog(RegisterFrame.this,
                                        message,
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    } else {
                        // 读取错误响应内容
                        StringBuilder errorResponse = new StringBuilder();
                        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                errorResponse.append(responseLine.trim());
                            }
                        }

                        String errorMessage = "注册失败";
                        // 尝试从响应中解析错误信息
                        if (errorResponse.length() > 0) {
                            errorMessage = errorResponse.toString();
                        } else {
                            errorMessage += ": " + responseCode;
                        }

                        System.err.println(errorMessage);
                        JOptionPane.showMessageDialog(RegisterFrame.this,
                                errorMessage,
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    System.err.println("发生异常: " + ex.getMessage());
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(RegisterFrame.this,
                            "注册失败: " + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }

    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(300, 35)); // 设置更大的宽度
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textField.setBackground(Color.WHITE);
        textField.setForeground(new Color(51, 51, 51));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(8, 10, 8, 10)
        ));
    }

    private void styleComboBox(JComboBox<?> comboBox) {
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        comboBox.setBackground(Color.WHITE);
        comboBox.setForeground(new Color(51, 51, 51));
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(8, 10, 8, 10)
        ));
    }

    private void styleButton(JButton button) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        button.setBackground(new Color(245, 245, 245));
        button.setForeground(new Color(51, 51, 51));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(8, 15, 8, 15)
        ));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(235, 235, 235));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(245, 245, 245));
            }
        });
    }

    private void styleRegisterButton(JButton button) {
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        button.setBackground(new Color(29, 185, 84)); // 使用Spotify风格的绿色
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        button.setPreferredSize(new Dimension(300, 45)); // 增加按钮大小

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(0, 102, 204));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(0, 120, 215));
            }
        });
    }
}